package org.happyinsure.structure;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class TableModel extends AbstractTableModel {
	
	private static final long serialVersionUID = 1L;
	private static boolean APPEND = false;
	
	private final List<Row> data = new ArrayList<>();
	
	public TableModel() throws Exception {
		File file = new File("data/data.csv");
		file.getParentFile().mkdirs();
		file.createNewFile();
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		String line = null;
		while ((line = bufferedReader.readLine())!= null) {
			String [] cells = line.split(Row.separator);
			Row row = new Row();
			for (int i=0; i<Row.getColumnCount(); i++)
				row.setCell(i, cells[i].trim());
			data.add(row);
		}
		bufferedReader.close();
		
		System.out.println(data);
	}

	@Override
	public int getRowCount() {
		return data.size();
	}

	@Override
	public int getColumnCount() {
		return Row.getColumnCount();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return data.get(rowIndex).getCell(columnIndex);
	}
	
	@Override
	public String getColumnName(int index) {
		return Row.getColumnName(index);
	}
	
	@Override
	public boolean isCellEditable(int row, int column) {
		return true;
	}
	
	public void save() throws IOException {
		File file = new File("data/data.csv");
		BufferedWriter writer = new BufferedWriter(new FileWriter(file, APPEND));
		for (Row row : data) {
			writer.write(row.toString());
			writer.newLine();
		}
		writer.close();
	}

}
